<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable
                    @clear="getuserList">
            <el-button slot="append" icon="el-icon-search" @click="getuserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userlist" border stripe>
        <el-table-column
          label="#"
          type="index">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="email"
          label="电子邮箱">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话号">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色名称">
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态">
          <template slot-scope="scope">
            <el-switch @change="userstatechange(scope.row)"
                       v-model="scope.row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" circle size="mini"
                         @click="showeditdialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" circle size="mini"
                         @click="open(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" circle size="mini"
                          @click="showsetRoledialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--   分页   -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--添加用户的对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClosed('addFormRef')">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="addForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser('addFormRef')">确 定</el-button>
  </span>
    </el-dialog>

    <!--修改用户的对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClosed('editFormRef')">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser('editFormRef')">确 定</el-button>
  </span>
    </el-dialog>
    <!--分配角色的对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoledialogVisible"
      width="50%"
      @close="setRoleDialogClosed('setRoleFormRef')">
      <el-form ref="setRoleFormRef" :model="setRoleForm">
        <el-form-item label="当前用户：" prop="username">
          <span>{{setRoleForm.username}}</span>
        </el-form-item>
        <el-form-item label="当前角色：" prop="role">
          <span>{{setRoleForm.role_name}}</span>
        </el-form-item>
        <el-form-item label="分配新角色：" prop="role">
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                      <el-option
                        v-for="item in roleNameList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                      </el-option>
                    </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRole('setRoleFormRef')">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: 'user',
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const checkphone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) {
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userlist: [],
      total: 0,
      dialogVisible: false,
      editdialogVisible: false,
      setRoledialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        checkPass: ''
      },
      editForm: {
        id: '',
        email: '',
        mobile: ''
      },
      setRoleForm: {
        id: '',
        username: '',
        role_name: ''
      },
      addFormRules: {
        password: [
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ],
        checkPass: [
          {
            validator: validatePass2,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [{
          required: true,
          validator: checkphone,
          trigger: 'blur'
        }]
      },
      editFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [{
          required: true,
          validator: checkphone,
          trigger: 'blur'
        }]
      },
      roleNameList : [],
      selectedRoleId: ''
    }
  },
  created () {
    this.getuserList()
  },
  methods: {
    async getuserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getuserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getuserList()
    },
    async userstatechange (userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        userinfo.mg_state = !userinfo.mg_state
      } else {
        this.$message.success('修改用户信息成功')
      }
    },
    isCellPhone (val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    addDialogClosed (refForm) {
      this.$refs[refForm].resetFields()
    },
    editDialogClosed (refForm) {
      this.$refs[refForm].resetFields()
    },
    setRoleDialogClosed (refForm) {
      this.$refs[refForm].resetFields()
    },
    addUser (refForm) {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addForm)
          console.log(res)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败')
          } else {
            this.$message.success('添加用户成功')
            this.dialogVisible = false
            this.getuserList()
          }
        } else {
          return false
        }
      })
    },
    editUser (editFormRef) {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          console.log(res)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          } else {
            this.$message.success('编辑用户成功')
            this.editdialogVisible = false
            this.getuserList()
          }
        } else {
          return false
        }
      })
    },
    async showeditdialog (id) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('查询用户信息失败')
      } else {
        this.editForm = res.data
      }
    },
    open (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          this.getuserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async saveRole (refForm) {
        if(!this.selectedRoleId){
          return this.$message.error('请选择要分配的角色!')
        }
        console.log('this.setRoleForm.id=='+this.setRoleForm.id)
      const { data: res } = await this.$http.put(`users/${this.setRoleForm.id}/role`,{
        rid: this.selectedRoleId
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.getuserList()
        this.$message({
          type: 'success',
          message: res.meta.msg
        })
        this.setRoledialogVisible = false
      }
    },
    async showsetRoledialog (row) {
      this.setRoledialogVisible = true
      this.setRoleForm.id = row.id
      this.setRoleForm.username = row.username
      this.setRoleForm.role_name = row.role_name
      const { data: res } = await this.$http.get('roles')
      if(res.meta.status !== 200){
        this.$message.error(res.meta.msg)
      }
      this.roleNameList = res.data
    }
  }
}
</script>

<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 15px;
    font-size: 12px;
  }

  .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  }

  .el-table {
    margin-top: 15px;
    font-size: 12px;
  }

  .el-pagination {
    margin-top: 15px;
  }
</style>
